# -*- coding:utf-8 -*-
#!/usr/bin/python
import sqlite3
import re 
import requests
from urlparse import urlunparse
from urllib import urlopen

"""
    @note: configuration test
"""

class MisConfigurationTest(object):
    
    def __init__(self,host,database):
        self.host=host
        self.database=database
    
    def CheckHTTPMethod(self,url):
    # detect http method
        r=requests.options(url)
        if r.status_code==200:
            try:
                methods=r.headers['allow']
                if re.search(r'TRACE|PUT|DELETE',methods,re.I):
                    print "Among HTTP methods (%s),one or more is likely to be exploited" % methods
            except:
                pass
    
    def CheckBackup(self):
        # check webserver misconfiguration vulnerabilities
        ''' unreferenced file:after and instead these extensions
        '''
#         print "[--ConfigurtaionTest--]"
        file_backups=['.bak','.old','~','.tmp','.copy','.orig','.dev','.src','.txt','.swp']
        conn=sqlite3.connect(self.database)
        cur=conn.cursor()
        path_lists=cur.execute("select path from stat").fetchall()
        conn.commit()
        conn.close()
        for path in path_lists:
            url=urlunparse(('http',self.host,path[0],'','',''))
            for ext in file_backups:
                ext_url_after=url+ext
                response=urlopen(ext_url_after)
                if response.code==200:
                    print ext_url_after,"is likely backup file."
                ext_url_instead=url[:url.rfind(".")]+ext
                response.close()
                response=urlopen(ext_url_instead)
                if response.code==200:
                    print ext_url_instead,"is likely backup file."
                response.close()
    
    def CheckAdmin(self):
        # analyze robots.txt
        robot_url=urlunparse(('http',self.host,'robots.txt','','',''))
        robot_content=urlopen(robot_url).read()
        result=re.search(r':\s*(\S*admin.*)\n',robot_content,re.I)
        if result:
            admin_url=urlunparse(('http',self.host,result.group(1),'','',''))
            print admin_url,"is likely admin entry."
        
    
    def check(self):

        #checkmethod
        url_method=urlunparse(('http',self.host,'','','','')) 
        self.CheckHTTPMethod(url_method)
        self.CheckBackup()
        